#include "musicslider.h"
#include "ui_musicslider.h"

MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);
    // 初始情况下，还没有开始播放，将当前播放进度设置为0
    currentPos = 0;
    maxWidth = width();
    moveSlider();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    // 注意：QMouseEvent中的pos()为⿏标相对于widget的坐标，不是相当于screen
    // 因此⿏标位置的 x 坐标可直接作为outLine的宽度
    currentPos = event->pos().x();
    moveSlider();
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    // 如果⿏标不在MusicSlider的矩形内，不进⾏拖拽
    QRect rect = QRect(0,0,width(),height());
    QPoint pos = event->pos();
    if(!rect.contains(pos))
    {
        return;
    }

    // 根据⿏标滑动的位置更新outLine的宽度
    if(event->buttons() == Qt::LeftButton)
    {
        // 验证：⿏标点击的x坐标是否越界，如果越界将其调整到边界
        currentPos = event->pos().x();
        if(currentPos < 0)
        {
            currentPos = 0;
        }

        if(currentPos > maxWidth)
        {
            currentPos = maxWidth;
        }

        moveSlider();
    }

}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSlider();

    emit setMusicPositionslider((float)currentPos/(float)maxWidth);
}

void MusicSlider::moveSlider()
{
    // 根据当前进度设置外部滑动条的位置
//    ui->outLine->setMaximumWidth(currentPos);
    ui->outLine->setGeometry(9,9,currentPos,2);
    ui->inLine->setGeometry(currentPos,9,maxWidth-currentPos,2);
}

void MusicSlider::setStep(float bf)
{
    currentPos = maxWidth*bf;
    moveSlider();
}
